<template>
  <div class="passport-area flx-row-c-c">
    <div class="box-area box-size">
      <div class="login-tab-area flx-row-c-c">
        <div
          class="item"
          :class="{ active: active == index }"
          v-for="(item, index) in tabList"
          :key="index"
          @click="active = index"
        >
          {{ item }}
        </div>
      </div>
      <div class="login-main-area flx-col-s-c">
        <Spin :withIcon="true" v-if="loading"></Spin>
        <template v-if="active == 0">
          <div class="flx-row-bw-c w-p-100 mg-b-15">
            <div class="title f-14 c-d2 w-80">手机号码</div>
            <Input
              size="large"
              placeholder="请输入手机号码"
              type="text"
              v-model.trim="userAccount"
              maxlength="11"
              @keyup.enter="login"
            />
          </div>
          <div class="flx-row-bw-c w-p-100 mg-b-15">
            <div class="title f-14 c-d2 w-80" style="letter-spacing: 32px">
              密码
            </div>
            <Input
              size="large"
              name="login-password"
              type="password"
              v-model="password"
              placeholder="请输入密码"
              @keydown="keydown($event)"
              maxlength="30"
              autocomplete="off"
              @keyup.enter="login"
            />
          </div>
        </template>
        <template v-if="active == 1">
          <div class="flx-row-bw-c w-p-100 mg-b-15">
            <div class="title f-14 c-d2 w-80">手机号码</div>
            <Input
              size="large"
              type="text"
              v-model.trim="phone"
              placeholder="请输入手机号码"
              maxlength="11"
              autocomplete="new-password"
              @keyup.enter="login"
            />
          </div>
          <div class="flx-row-bw-c w-p-100 mg-b-15">
            <div class="title f-14 c-d2 w-80" style="letter-spacing: 8px">
              验证码
            </div>
            <Input
              size="large"
              type="text"
              v-model.trim="code"
              placeholder="请输入验证码"
              maxlength="6"
              @keyup.enter="login"
            />
            <div
              class="user-normal-button code-button"
              style="width: 100px"
              :class="[
                getCodeAvailable ? 'user-normal-button' : 'forbid-button',
              ]"
              @click="getCode"
            >
              {{ getCodeContent }}
            </div>
          </div>
        </template>

        <slider class="mg-b-15" @success="sliderSuccess" ref="slider"></slider>
        <div class="flx-row-bw-c w-p-100 mg-b-15">
          <Checkbox class="radio-mg-r-20" v-model="remember"> 记住我</Checkbox>
          <router-link to="/login/forget" class="font-bottom f-14"
            >忘记密码</router-link
          >
        </div>
        <div
          class="user-strong-button big-button-size-40 w-p-100 mg-b-15"
          @click="checkForm"
        >
          登录
        </div>
        <span class="c-d2 f-14"
          >还没有190账户？<router-link to="/login/re" class="font-b-bottom"
            >立即注册</router-link
          ></span
        >
      </div>
    </div>
  </div>
</template>

<script>
import { getPublicKey } from "@/api/user";
import { login, getCode } from "@/api/user";
import { validMobile } from "@/utils/validate.js";
import JSEncrypt from "jsencrypt";
import { mapActions } from "vuex";
export default {
  components: {
    slider: () => import("_c/slider/slider.vue"),
  },
  name: "VipLogin",
  data() {
    return {
      loading: false,

      tabList: ["密码登录", "短信登录"],
      active: 0,
      remember: false,

      // 表单
      userAccount: "",
      password: "",
      phone: "",
      code: "",

      // 获取验证码数据
      // 是否可以获取验证码
      getCodeAvailable: true,
      // 获取验证码按钮上的文字
      getCodeContent: "获取验证码",
      // 获取验证码定时器
      getCodeInterval: null,

      // 验证数据
      checkSuccess: false,
    };
  },
  created() {
    this.getPublicKey();
    let res = this.$storage.getRememberMe();
    if (res) {
      this.userAccount = res;
      if (validMobile(res)) {
        this.phone = res;
      }
      this.remember = true;
    }
  },
  methods: {
    ...mapActions(["getUserData", "getAmountData"]),
    async getPublicKey() {
      if (!this.$storage.getPublicKey()) {
        let res = await getPublicKey();
        if (res.code == 200) {
          this.$storage.setPublicKey(res.data);
        }
      }
    },
    getEncrypt(data) {
      let encrypt = new JSEncrypt();
      // 设置公钥
      encrypt.setPublicKey(this.$storage.getPublicKey());
      return encrypt.encrypt(data);
    },
    sliderSuccess() {
      this.checkSuccess = true;
    },
    /**
     * @description 获取验证码
     */
    async getCode() {
      if (!this.getCodeAvailable) return;
      if (!validMobile(this.phone)) {
        this.$Message.warning("请输入正确的手机号码！");
        return;
      }
      this.loading = true;
      let res = await getCode(this.phone);

      if (res.code == 200) {
        // this.code = res.data.vcode;
        this.getCodeAvailable = false;
        let i = 60;
        this.getCodeContent = `${i--}秒后再获取`;
        this.getCodeInterval = setInterval(() => {
          if (i <= 1) {
            this.getCodeContent = "获取验证码";
            this.getCodeAvailable = true;
            clearInterval(this.getCodeInterval);
            return;
          }
          this.getCodeContent = `${i--}秒后再获取`;
        }, 1000);
        this.$Message.success("验证码已经发送，请注意查收！");
      }
      this.loading = false;
    },
    /**
     * @description 检查表单
     */
    checkForm() {
      if (this.active == 0) {
        if (this.userAccount == null || this.userAccount == "") {
          this.$Message.warning("请输入手机号码！");
          return;
        }
        if (this.password == null || this.password == "") {
          this.$Message.warning("请输入密码！");
          return;
        }
      } else {
        if (!validMobile(this.phone)) {
          this.$Message.warning("请输入正确的手机号码！");
          return;
        }
        if (this.code == null || this.code == "") {
          this.$Message.warning("请输入验证码！");
          return;
        }
      }
      if (!this.checkSuccess) {
        this.$Message.warning("请进行滑块验证！");
        return;
      }
      this.submit();
    },
    /**
     * @description 提交表单
     */
    async submit() {
      this.loading = true;
      let params;
      if (this.active == 0) {
        params = {
          account: this.userAccount,
          password: this.getEncrypt(this.password),
          type: 0,
          source: 0,
        };
      } else {
        params = {
          account: this.phone,
          code: this.code,
          type: 1,
          source: 0,
        };
      }
      let res = await login(params);
      if (res.code == 200) {
        if (this.remember) {
          if (this.active == 0) {
            this.$storage.setRememberMe(this.userAccount);
          } else {
            this.$storage.setRememberMe(this.phone);
          }
        } else {
          this.$storage.setRememberMe("");
        }
        this.$storage.setLoginSource(0);
        this.$Message.success("登录成功！");
        this.$store.commit("setToken", res.data);
        this.$token.setRT(res.data);
        this.getUserData();
        this.getAmountData();
        setTimeout(() => {
          let path = this.$storage.getToLoginRoute();
          this.$storage.setToLoginRoute("/");
          // if (path) {
          //   window.location.replace(path);
          // } else {
          //   window.location.replace("/");
          // }
          if (path) {
            path === "/" && this.$router.replace(path);
            try {
              path !== "/" && this.$router.replace(JSON.parse(path));
            } catch (error) {
              this.$router.replace({ path: "/" });
            }
          } else {
            this.$router.replace("/");
          }
        }, 1000);
      } else {
        this.$refs.slider.reset();
      }
      this.loading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.box-size {
  width: 700px;
}
.login-tab-area {
  width: 100%;
  padding-top: 50px;
  border-bottom: #d8d8d8 solid 1px;
  .item {
    width: 165px;
    border-bottom: transparent solid 2px;
    font-size: 22px;
    text-align: center;
    color: rgba(#3d3d3d, 0.7);
    cursor: pointer;
    margin: 0 10px;
    line-height: 40px;
    &:hover {
      color: #3d3d3d;
    }
    &.active {
      color: #3d3d3d;
      border-color: #F68A0C;
    }
  }
}
.login-main-area {
  padding: 50px 160px 70px;
  position: relative;
}
.mg-b-15 {
  margin-bottom: 15px;
}
.title {
  flex-shrink: 0;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
}
.w-50 {
  width: 50px;
}
.w-80 {
  width: 80px;
}
</style>
